$(function () {
    // setting对象中包含zTree的设置属性
    var setting = {
        "view": {
//设置自定义图标
            "addDiyDom": showMyIcon,
            "addHoverDom": addHoverDom,
            "removeHoverDom": removeHoverDom
        },
        "data": {
            "key": {
                "url": "notExistsProperty" // 阻止点击节点后跳转
            }
        }
    };
//发送ajax请求获取zNodes数据
    $.ajax({
        "url": "/menu/get/whole/tree",
        "type": "post",
        "dataType": "json",
        "success": function (response) {
            var result = response.result;
            if (result == "SUCCESS") {
//用于显示树型结构的节点数据
                var zNodes = response.data;
                // 执行树形结构的初始操作
                $.fn.zTree.init($("#treeDemo"), setting, zNodes);
            }
            else {
                layer.msg("加载菜单数据失败！原因是：" + response.message);
            }
        }

    })

    //确定添加
    $("#menuAddBtn").click(function () {
        // 收集表单填写的数据
        var name = $.trim($("#menuAddModal [name='name']").val());
        var url = $.trim($("#menuAddModal [name='url']").val());
        var icon = $("#menuAddModal [name='icon']:checked").val();
        if(name == null || name == "") {
            layer.msg("请填写菜单项名称！");
            return ;
        }

        if(url == null || url == "") {
            layer.msg("请填写菜单项对应的访问地址！");
            return ;
        }
        // 发送Ajax请求
        $.ajax({
            "url":"/menu/save",
            "type":"post",
            "dataType":"json",
            "data":{
                "name":name,
                "url":url,
                "pid":window.menuId,   // 当前操作的节点是新节点的父节点
                "icon":icon
            },
            "success":function(response){

                var result = response.result;

                if(result == "SUCCESS") {
                    layer.msg("操作成功！");
                    //重新加载树状图数据  重新刷新
                    initWholeTree();
                }

                if(result == "FAILED") {
                    layer.msg(response.message);
                }

            },
            "error":function(response){
                layer.msg(response.message);
            }
        });


        $("#menuAddModal").modal("hide");
    });



})


//更换图标                    demo
function showMyIcon(treeId, treeNode) {
    console.log(treeId);
    console.log(treeNode);

    // 获取当前节点的id
    var currentNodeId=treeNode.tId;
    // 获取新的class值用于替换
    var newClass=treeNode.icon;
    //在当前节点id之后附加“_ico”得到目标span的id
    var targetSpanId = currentNodeId + "_ico";
    $('#'+targetSpanId).removeClass().addClass(newClass).css("background","");
}
function generateBtnGrp(treeNode) {
    // 获取当前节点的id（HTML中li标签的id）
    var tid=treeNode.tId;
    // 组装按钮组所在的span的id
    var btnGrpSpanId=tid+"_btnGrp";
    // 生成span标签对应的jQuery对象
    var $span = $("<span id='"+btnGrpSpanId+"'></span>");

    // 获取当前节点在数据库中的id值
    var menuId=treeNode.id;
    // 获取当前节点的level值
    var level=treeNode.level;

    // 声明三种按钮
    var addBtn = "<a onclick='showAddModal(this)' id='"+menuId+"' class='btn btn-info dropdown-toggle btn-xs' style='margin-left:10px;padding-top:0px;' title='添加子节点'>&nbsp;&nbsp;<i class='fa fa-fw fa-plus rbg'></i></a>";
    var editBtn = "<a onclick='showEditModal(this)' id='"+menuId+"' class='btn btn-info dropdown-toggle btn-xs' style='margin-left:10px;padding-top:0px;' title='编辑节点'>&nbsp;&nbsp;<i class='fa fa-fw fa-edit rbg'></i></a>";
    var removeBtn = "<a onclick='showConfirmModal(this)' id='"+menuId+"' class='btn btn-info dropdown-toggle btn-xs' style='margin-left:10px;padding-top:0px;' title='删除节点'>&nbsp;&nbsp;<i class='fa fa-fw fa-times rbg'></i></a>";

    // 根据level进行判断
    if (level==0){
        $span.append(addBtn);
    }
    if(level == 1) {
        if(treeNode.children.length > 0) {
            $span.append(addBtn+" "+editBtn);
        }else{
            $span.append(addBtn+" "+editBtn+" "+removeBtn);
        }
    }
    if(level == 2) {
        $span.append(editBtn+" "+removeBtn);
    }

    return $span;
}



//鼠标悬浮
function addHoverDom(treeId, treeNode){
//如果按钮存在 则不用添加
    var btnGrpSpanId = treeNode.tId + "_btnGrp";

    var btnGrpSpanLength = $("#"+btnGrpSpanId).length;

    if(btnGrpSpanLength > 0) {
        return ;
    }


    //获取按钮组
    var $btnGrpSpan=generateBtnGrp(treeNode);
//找到菜单中的超连接
    var anchorId =treeNode.tId+"_a";
    $("#"+anchorId).append($btnGrpSpan);

}

//鼠标移出
function removeHoverDom(treeId, treeNode) {
    // 找到按钮组 删除
    var btnGrpSpanId = treeNode.tId + "_btnGrp";
    // 删除对应的元素
    $("#"+btnGrpSpanId).remove();
}

//添加子节点
//添加菜单
function showAddModal(currentBtn) {

    // 将当前节点的id存入全局变量
    window.menuId = currentBtn.id;

    // 打开模态框
    $("#menuAddModal").modal("show");

}


//添加成功之后回显到菜单的主页面

function   initWholeTree() {
    //setting对象中包括zTree的属性
    var setting={
        "view": {
            "addDiyDom": showMyIcon,
            "addHoverDom": addHoverDom,
            "removeHoverDom": removeHoverDom
        },
        "data": {
            "key": {
                "url": "notExistsProperty" // 阻止点击节点后跳转
            }
        }
    }

    //发送ajax请求
    $.ajax({
        url:"/menu/get/whole/tree",
        type:"post",
        dataType:"json",
        success:function (ajaxResult) {
            var result=ajaxResult.result;
            if(result=="SUCCESS"){
                //用于显示树形结果的节点数据
                var zNodes=ajaxResult.data;

                $.fn.zTree.init($("#treeDemo"),setting,zNodes);
            }else{
                layer.msg("加载菜单数据失败！原因是："+response.message);
            }
        }
    })
}

//修改 打开模态框 回显数据
function showEditModal(currentBtn) {
    // 获取当前节点的id存入全局变量
    window.menuId = currentBtn.id;
    //打开模态框
    $("#menuEditModal").modal("show");
    //发送ajax请求
    // 发送请求查询Menu对象

    //发送ajax请求
$.ajax({

    "url": "/menu/get/" + window.menuId,
    "type": "get",
    "dataType": "json",
    "success":function (response) {
        var result=response.result;
if(result=="SUCCESS"){
    // 从响应数据中获取Menu对象
    var menu = response.data;

    // 获取各个属性值
    var name = menu.name;

    var url = menu.url;

    var icon = menu.icon;

    // 设置各个对应的表单项
    $("#menuEditModal [name='name']").val(name);

    $("#menuEditModal [name='url']").val(url);

    // radio需要让value值和后端查询到的icon一致的设置为被选中
    $("#menuEditModal [name='icon'][value='" + icon + "']").attr("checked", true);
}

        if (result == "FAILED") {
            layer.msg(response.message);
        }

    },
    "error": function (response) {
        layer.msg(response.message);
    }

})

    //确定修改
    //确定修改
    $("#menuEditBtn").click(function () {

        // 收集表单填写的数据
        var name = $.trim($("#menuEditModal [name='name']").val());
        var url = $.trim($("#menuEditModal [name='url']").val());
        var icon = $("#menuEditModal [name='icon']:checked").val();

        if (name == null || name == "") {
            layer.msg("请填写菜单项名称！");
            return;
        }

        if (url == null || url == "") {
            layer.msg("请填写菜单项对应的访问地址！");
            return;
        }

        // 发送Ajax请求
        // 发送Ajax请求
        $.ajax({
            "url": "/menu/update",
            "type": "post",
            "dataType": "json",
            "data": {
                "id": window.menuId,
                "name": name,
                "url": url,
                "icon": icon
            },
            "success": function (response) {

                var result = response.result;

                if (result == "SUCCESS") {
                    layer.msg("操作成功！");

                    initWholeTree();
                }

                if (result == "FAILED") {
                    layer.msg(response.message);
                }

            },
            "error": function (response) {
                layer.msg(response.message);
            }
        });


        $("#menuEditModal").modal("hide");
    });

}

//删除
function showConfirmModal(currentBtn) {
    // 获取当前节点的id存入全局变量
    window.menuId = currentBtn.id;
    var name=$(currentBtn).parent().prev().text();
    var  r=confirm("确认删除"+name+"菜单吗?");
    if(r==false){
        return;
    }
    $.ajax({
        "url":"/menu/delete/"+window.menuId,
        "type":"get",
        "dataType":"json",
        "success":function(response){

            if(response.result == "SUCCESS") {
                layer.msg("删除成功！");
                initWholeTree();
            }

            else {
                layer.msg("删除失败！请联系管理员!");
            }

        },

    });







}


